<template>
  <a-layout>
    <a-layout-content
      :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }"
    >
      <p>
        <a-form layout="inline" :model="param">
          <a-form-item>
            <a-input v-model:value="param.name" placeholder="名称" />
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="handleQuery({ page: 1, size: pagination.pageSize })">
              查询
            </a-button>
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="add()">
              新增
            </a-button>
          </a-form-item>
        </a-form>
      </p>
      <a-table
        :columns="columns"
        :row-key="record => record.id"
        :data-source="ebooks"
        :pagination="pagination"
        :loading="loading || !categoryMap.size"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'cover'">
            <a-image :src="record.cover" alt="图片加载失败" style="width:80px;height:80px" />
          </template>
          <template v-if="column.key === 'category'">
            <span>
              {{ getCategoryName(record.category1Id) }}/{{ getCategoryName(record.category2Id) }}
            </span>
          </template>
          
          <!-- <template v-if="column.dataIndex === 'action'">
            <a-space size="small">
              <a-button type="primary" @click="edit(record)">编辑</a-button>
              <a-popconfirm
                title="删除后不可以恢复，确认删除?"
                ok-text="是"
                cancel-text="否"
                @confirm="handleDelete(record.id)"
              >
                <a-button type="danger">删除</a-button>
              </a-popconfirm>
            </a-space>
          </template> -->
          <template v-if="column.dataIndex === 'action'">
            <a-space size="small">
              <a-button type="primary"  >
                <router-link :to="'/admin/doc?ebookId='+record.id"> 文档管理</router-link>
              </a-button>  

              <a-button type="primary"  @click="edit(record)">
                编辑
              </a-button>
             <a-popconfirm
                title="删除后不可以恢复，确认删除?"
                ok-text="是"
                cancel-text="否"
                @confirm="handleDelete(record.id)"
             >
               <a-button type="danger" >
                 删除
               </a-button>
             </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-layout-content>
  </a-layout>
  <!-- 定义模态框 -->
  <a-modal
      title="电子书表单"
      v-model:visible="modalVisible"
      :confirm-loading="modalLoading"
      @ok="handleModalOk"
  >
    <a-form :model="ebook" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
      <a-form-item label="封面">
          <a-input v-model:value="ebook.cover" />
      </a-form-item>
      <a-form-item label="名称">
        <a-input v-model:value="ebook.name" />
      </a-form-item>
      <a-form-item label="分类">
        <a-cascader v-model:value="categoryIds" 
          :field-names="{ label: 'name', value: 'id', children: 'children' }"
          :options="level1"  />
      </a-form-item >
      <a-form-item label="分类一">
        <a-input v-model:value="ebook.category1Id" disabled />
      </a-form-item>
      <a-form-item label="分类二">
        <a-input v-model:value="ebook.category2Id" disabled />
      </a-form-item>
      <a-form-item label="描述">
        <a-textarea v-model:value="ebook.description" type="textarea" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script lang="ts" setup>
import axios from 'axios';
import { ref, onMounted, computed } from 'vue';
import { message } from 'ant-design-vue';
import { Tool } from '@/utils/tool.ts';
// 定义数据类型
interface Category {
  id: string;
  name: string;
  children?: Category[];
}

// 电子书数据
const ebooks = ref([] as any[]); // 初始化数组
const ebook = ref({} as any);
const param = ref({ name: '' } as any);
const modalVisible = ref(false);
const modalLoading = ref(false);

// 分页参数
const pagination = ref({   
  current: 1,
  pageSize: 5,
  total: 0
} as any);
const loading = ref(false);

// 表格列定义
const columns = [
  {
    title: '封面',
    key: 'cover',
    dataIndex: 'cover',
  },
  {
    title: '名称',
    dataIndex: 'name'
  },
  {
    title: '分类',
    key: 'category',
    dataIndex: 'category'
  },
  {
    title: '文档数',
    dataIndex: 'docCount'
  },
  {
    title: '阅读数',
    dataIndex: 'viewCount'
  },
  {
    title: '点赞数',
    dataIndex: 'voteCount'
  },
  {
    title: 'Action',
    key: 'action',
    dataIndex: 'action'
  }
];

// 分类相关数据
const categoryIds = ref([] as string[]); // 保存选中分类数组
const level1 = ref([] as Category[]); // 保存一级分类数据
const categoryMap = ref(new Map<string, string>()); // 分类ID到名称的映射表

// 初始化分类映射表
const initCategoryMap = () => {
  if (categorys.value) {
    categorys.value.forEach((category: Category) => {
      categoryMap.value.set(category.id, category.name);
    });
  }
};

// 根据ID获取分类名称，处理不存在的情况
const getCategoryName = (cid: number | string): string => {
  const cidStr = String(cid);
  return categoryMap.value.get(cidStr) || '未分类';
};

let categorys = ref([] as Category[]);

// 获取分类数据
const handleQueryCategory = () => {
  loading.value = true;
  axios.get("http://localhost:8080/obwiki/category/all").then((resp) => {
    loading.value = false;
    const data = resp.data;
    categorys.value = data.content || [];
    
    if (data.success) {
      console.log("原始分类数组", categorys.value);
      level1.value = Tool.array2Tree(categorys.value, 0);
      console.log("分类树形结构：", level1.value);
      
      // 初始化分类映射表
      initCategoryMap();
      
      // 加载完分类后再加载电子书
      handleQuery({
        page: 1,
        size: pagination.value.pageSize
      });
    } else {
      message.error(data.message);
    }
  });
};

/*
* 数据查询
*/
const handleQuery = (params: any) => {
  // 等待分类数据加载完成
  if (!categoryMap.value.size) {
    return;
  }
  
  loading.value = true;
  axios.get("http://localhost:8080/obwiki/ebook/list", {
    params: {
      page: params.page,
      size: params.size,
      name: param.value.name
    }
  }).then((resp) => {
    loading.value = false;
    const data = resp.data;
    if (data.success) {
      ebooks.value = data.content.list || [];
      pagination.value.current = params.page;
      pagination.value.total = data.content.total || 0;
    }
  });
};     

/*
* 表格分页触发
*/
const handleTableChange = (pagination: any) => {
  console.log("分页参数：", pagination);
  handleQuery({
    page: pagination.current,
    size: pagination.pageSize
  });
};

const edit = (record: any) => {
  modalVisible.value = true;
  ebook.value = Tool.copy(record);
  
  // 设置级联选择器的值
  if (record.category1Id && record.category2Id) {
    categoryIds.value = [String(record.category1Id), String(record.category2Id)];
  }
  
  console.log('编辑记录:', record);
};

const handleDelete = (id: number) => {
  axios.delete(`http://localhost:8080/obwiki/ebook/delete/${id}`).then((resp) => {

    if (resp.data.success) {
      // 重新加载列表
      handleQuery({
        page: pagination.value.current,
        size: pagination.value.pageSize
      });
    }
  });
  console.log('删除ID:', id);
};

const handleModalOk = () => {
  modalLoading.value = true;
  
  // 从级联选择器获取分类ID
  if (categoryIds.value && categoryIds.value.length >= 2) {
    ebook.value.category1Id = categoryIds.value[0];
    ebook.value.category2Id = categoryIds.value[1];
  }
  
  axios.post("http://localhost:8080/obwiki/ebook/save", ebook.value).then(resp => {
    const data = resp.data;
    if (data.success) {
      modalLoading.value = false;
      modalVisible.value = false;
      // 重新加载列表
      handleQuery({
        page: pagination.value.current,
        size: pagination.value.pageSize
      });
    } else {
      message.error(data.message);
    }
  });
};

const add = () => {
  modalVisible.value = true;
  ebook.value = {};
  categoryIds.value = []; // 清空分类选择
};

// 组件挂载时加载分类数据
onMounted(() => {
  handleQueryCategory();
});
</script>